<template>
  <div>
    <!-- 顶部栏 -->
    <van-nav-bar
      title="登陆"
      left-text="返回"
      left-arrow
      @click-left="$router.go(-1)"
    />
    <!-- 输入框 -->
    <van-form @submit="onSubmit">
      <van-field
        required
        v-model="mobile"
        name="mobile"
        label="手机号"
        placeholder="请输入手机号"
        :rules="[
          { required: true, message: '请填写用户名' },
          {
            pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
            message: '手机号格式不对'
          }
        ]"
      />
      <van-field
        required
        v-model="code"
        name="code"
        label="验证码"
        placeholder="请输入验证码"
        :rules="[
          { required: true, message: '请填写密码' },
          { pattern: /^\d{6}$/, message: '验证码格式不对' }
        ]"
      />
      <div style="margin: 16px;">
        <van-button
          color="pink"
          round
          block
          type="info"
          native-type="submit"
          :disabled="isLoding"
          :loading="isLoding"
          loading-text="登陆中...."
        >
          提交
        </van-button>
      </div>
    </van-form>
  </div>
</template>

<script>
import { getLogin } from './user'
// 导入封装token方法的文件
import { saveToken } from '@/utils/token.js'
export default {
  name: 'login',
  data () {
    return {
      //   输入框双向绑定值
      mobile: '',
      code: '246810',
      // 设置布尔属性判断按钮的加载状态
      isLoding: false
    }
  },
  //   输入框数据处理
  methods: {
    onSubmit (value) {
      console.log(value)
      this.isLoding=true
      getLogin(value)
        .then(res => {
          console.log(res)
          this.$toast.success('登陆成功')
          //登陆成功的时候保存token
          saveToken(res.data.data)
          // 登陆成功的时候跳转
          this.$router.push({ path: '/home' })
        })
        // promise.catch 返还值并处理拒绝的情况
        .catch(err => {
          console.log(err)
          this.$toast.fail('账号或密码有错误')
        })
        // 通过最有一个promise.then,不管请求成功还是失败都会执行
        .then(() => {
          this.isLoding = false
        })
    }
  }
}
</script>

<style lang="less">
.van-nav-bar {
  //左边按钮
  .van-nav-bar__content {
    background-color: pink;

    .van-nav-bar__text {
      color: #fff;
    }
    .van-icon-arrow-left {
      color: #fff;
    }
  }
  //登陆
  .van-nav-bar__title {
    color: #fff;
  }
}
</style>
